using Godot;
using System;

using CurrentGame.Utils.Interpolation;

namespace CurrentGame.GUI;


public partial class PlacementHint : Control
{
	[Export]
	public string HintText
	{
		get
		{
			if (_textLabel == null) return "";
			return _textLabel.Text;
		}
		set
		{
			if (_textLabel != null) _textLabel.Text = value;
		}
	}

	[Export]
	public float InterpolationWeight
	{
		get => _interpolation.Weight;
		set => _interpolation.Weight = value;
	}

	[Export]
	public GamePlayGui Gui { get; set; }

	// private members
	private LerpInterpolation _interpolation;
	private bool _enabled = false, _updating = false;
	private Vector2 _currentPosition = Vector2.Zero;
	private Node2D _anchor;

	// Node reference
	private Label _textLabel;

	public PlacementHint()
	{
		_interpolation = new LerpInterpolation(0.01f, new Vector3(-1f, -1f, 0.0001f))
		{
			Vector3Value = new Vector3(0.0f, 0.0f, 0.0f)	// x, y, alpha
		};
		_interpolation.Teleport();
	}


	// GODOT - Callbacks
	public override void _Ready()
	{
		_textLabel = GetNode<Label>("HintLabel");
	}

	public override void _Process(double delta)
	{
		// Do interpolation
		if (_interpolation.Process(delta))
		{
			var current = _interpolation.Vector3Value;

			Modulate = new Color(1.0f, 1.0f, 1.0f, current.Z);
			Position = new Vector2(current.X, current.Y);
		}

		// Update destination
		if (_updating) UpdatePosition(_anchor.GlobalPosition);
	}


	// private functions
	private void UpdatePosition(Vector2 position)
	{
		if (_enabled)
		{
			position = Gui.GlobalToUi(position);
			_interpolation.Vector3Value = new Vector3(position.X, position.Y, 1.0f);
			_currentPosition = position;
		}
	}

	// Export interfaces
	public void SetAnchor(Node2D node)
	{
		_anchor = node;
	}

	public void EnableHint()
	{
		_enabled = true;
		_updating = true;
		_textLabel.Visible = true;
		_interpolation.Vector3Value = new Vector3(_currentPosition.X, _currentPosition.Y, 1.0f);
	}

	public void DisableHint()
	{
		_enabled = false;
        _interpolation.Vector3Value = new Vector3(_currentPosition.X, _currentPosition.Y, 0.0f);
    }

	// Private signals
	private void Singal_InterpolationStable(float v, Vector2 v2, Vector3 v3)
	{
		// Reach stable state after disabling hint
		if (!_enabled)
		{
			_updating = false;
			_textLabel.Visible = false;
		}
	}
}
